<template>
<div :style="{width: typeof width === 'number' ? width+'px' : width, height: typeof height === 'number' ? height+'px' : height}" class="undraggable">
  <div ref="table" style="width: 100%;height:100%"></div>
</div>
</template>

<script>
import {merge, cloneDeep} from 'lodash'
import { VTableSheet, VTable, TYPES } from '@visactor/vtable-sheet';
import { TableExportPlugin } from '@visactor/vtable-plugins';
import ExcelImport from './utils/excelImport.js';
import { InputEditor, DateInputEditor, TextAreaEditor  } from '@visactor/vtable-editors';
import NumberEditor from './editors/numberEditor/index.js';
import MultipleListEditor from './editors/multipleListEditor.js';
import SingleListEditor from './editors/singleListEditor.js';
import { commit, on, off } from '../../../store/tableSheet.js'
const inputEditor = new InputEditor();
const dateInputEditor = new DateInputEditor();
const textAreaEditor = new TextAreaEditor();
const numberEditor = new NumberEditor();
const singleListEditor = new SingleListEditor()
const multipleListEditor = new MultipleListEditor()
VTable.register.editor('inputEditor', inputEditor);
VTable.register.editor('numberEditor', numberEditor);
VTable.register.editor('dateEditor', dateInputEditor);
VTable.register.editor('textAreaEditor', textAreaEditor)
VTable.register.editor('listEditor', singleListEditor);
VTable.register.editor('multipleListEditor', multipleListEditor);

console.log('VTable TYPES', TYPES);
const defaultData = {
  showToolbar: true, //是否显示工具栏
  showFormulaBar: true, //是否显示公式栏
  showSheetTab: true, //是否显示工作表切换栏
  mainMenu: {
    show: true,  // 显示主菜单
    items: [
      {
        name: '导入',
        description: '导入数据',  // 鼠标悬停时的提示信息
      },
      {
        name: '导出',
        menuKey: TYPES.MainMenuItemKey.EXPORT_CURRENT_SHEET_XLSX,
        description: '导出当前表格为Excel格式'
      }
    ]
  },
  VTablePluginModules: [
  ],
  sheets: [
    // 员工数据表格页
    {
      sheetKey: 'Sheet1',
      sheetTitle: 'Sheet1',
      // heightMode: 'autoHeight', // 行高自适应
      // enableLineBreak: true, // 解析换行符
      // canvasHeight: 'auto', // 自动适应内容高度
      // heightMode: 'adaptive',
      containerFit: {
        width: true,   // boolean
        height: true   // boolean
      },
      tooltip: {
        isShowOverflowTextTooltip: true
      },
      columns: [
        { title: "姓名", width: 100, editorConfig: {
          type: 'multipleListEditor',
          values: ['女', '男', '未知']
        }},
        { title: "部门", width: 120, editorConfig: {
          type: 'listEditor',
          values: ['女', '男']
        }},
        { title: "职位", width: 120, editorConfig: {
          type: 'textAreaEditor'
        }},
        { title: "入职日期", width: 120, editorConfig: {
          type: 'dateEditor'
        }},
        { title: "工资", width: 100, editorConfig: {
          type: 'numberEditor'
        }},
        { title: "文件", width: 100, editorConfig: {
          disabled: true
        }},
      ],
      data: [
        ["张三", "技术部", "工程师", "2022-01-15", 12000, "文件1,123;文件,234"],
        ["李四", "市场部", "经理", "2020-06-20", 18000, "文件1,123;文件,234"],
        ["王五", "技术部", "高级工程师", "2021-03-10", 15000, "文件1,123;文件,234"],
        ["赵六", "人力资源", "专员", "2022-09-01", 9000, "文件1,123;文件,234"],
      ],
    }
  ],
}

export default {
  name: 'TableSheet',
  props: {
    height: {
      type: [Number, String],
      default: 400
    },
    width: {
      type: [Number, String],
      default: '100%'
    },
    data: {
      type: Object,
      default: () => {
        return {...defaultData}
      }
    }
  },
  inject: ['useConf'],
  components: {
  },
  data() {
    return {
    };
  },
  created() {},
  mounted() {
    this.createTable();
  },
  methods: {
    onTest(){
    },
    createTable() {
      let conf = this.useConf()
      const container = this.$refs.table
      this.excelImport = new ExcelImport()
      let localData = {}
      /**/
      if(!this.data || (this.data && Object.keys(this.data).length == 0)){
        localData = cloneDeep(defaultData)
      }else{
        localData = cloneDeep(this.data)
      }
      // TODO
      // localData = cloneDeep(defaultData)
      // console.log('sheetInstance', sheetInstance);
      // console.log('TYPES', TYPES);
      let initlocalData = ()=>{
        if(localData.mainMenu){
          localData.mainMenu.items.forEach(t=>{
            if(t.name === '导入'){
              t.onClick = async () => {
                try {
                  await this.excelImport.import({
                    tableInstance: this.sheetInstance.activeWorkSheet.tableInstance
                  })
                }catch(err){
                  this.$message.error(err.message)
                }
              }
            }
          })
        }
        localData.VTablePluginModules = [
          { module: TableExportPlugin,
            moduleOptions: {
              exportExcelOptions: {
                downloadFile: true,
                fileName: conf.__config__.label || '自定义报表'
              },
            }
          }
        ]
        localData.sheets.forEach(sheet=>{
          sheet.columns.forEach((column)=>{
            if(typeof column.editorConfig === 'object'){
              let {type, values, disabled} = column.editorConfig
              // console.log('type', type)
              if(type){
                column.editor = type
              }
              // console.log('disabled', disabled)
              if(disabled){
                merge(column, {
                  disableHover: true, editor: false, style: {
                    cursor: 'not-allowed'
                  }
                })
              }
            }
          })
        })
      }
      initlocalData()
      console.log('data', this.data)
      console.log('localData', localData)

      let sheetInstance = new VTableSheet(container, localData);
      this.localData = localData
      let registerEvent = ()=>{
        sheetInstance.activeWorkSheet.on(TYPES.WorkSheetEventType.SELECTION_CHANGED, ()=>{
          // console.log('sheetInstance.activeWorkSheet', sheetInstance.activeWorkSheet)
          let { editingCell, options, selection, tableInstance } = sheetInstance.activeWorkSheet
          let {startCol, endCol, startRow, endRow} = selection
          let {columns} = options
          let defaultStyle = {
            fontSize: 14,
            color: undefined,
            bgColor: undefined,
            fontWeight: undefined,
            fontStyle: undefined,
            lineThrough: false,
            underline: false,
          }
          let column = columns[startCol]
          let headerStyle = column.headerStyle || {
            ...defaultStyle,
            fontSize: 16,
            fontWeight: 'bold'
          }
          let columnStyle = column.style || {...defaultStyle}
          let columnEdit = {
            type: 'inputEditor',
            values: [],
            disabled: false
          }
          if(column.editorConfig){
            columnEdit.type = column.editorConfig.type || 'inputEditor'
            columnEdit.values = column.editorConfig.values || []
            columnEdit.disabled = column.editorConfig.disabled === true
          } else if(column.editor) {
            columnEdit.type = column.editor
          }
          // console.log('headerStyle', this.headerStyle)
          // console.log('columnStyle', this.columnStyle)
          // console.log('columnEdit', columnEdit)
          commit((state)=>{
            if(startRow === 0){
              state.showHeaderSetting = true
              state.showColumnSetting = false
            } else {
              state.showHeaderSetting = false
              state.showColumnSetting = true
            }
            state.headerStyle = headerStyle
            state.columnStyle = columnStyle
            state.columnEdit = columnEdit
          })
          off(['changeStyle', 'changeColumnEdit'])
          on('changeStyle', this.onChangeStyle)
          on('changeColumnEdit', this.onChangeColumnEdit)
        })
        ;['ADD_COLUMN', 'ADD_RECORD', 'DELETE_COLUMN', 'DELETE_RECORD', 'DRAG_SELECT_END', 'PASTED_DATA', 'RESIZE_COLUMN_END', 'RESIZE_ROW_END', 'CHANGE_CELL_VALUE'].forEach(eventName=>{
          sheetInstance.activeWorkSheet.tableInstance.on(VTable.TABLE_EVENT_TYPE[eventName], ()=>{
            this.save()
          })
        })
      }
      registerEvent()
      this.sheetInstance = sheetInstance;
    },
    onChangeStyle(type, data){
      // console.log('onChangeStyle', type, data)
      let { editingCell, options, selection, tableInstance} = this.sheetInstance.activeWorkSheet
      if(!selection) return
      let {startCol, endCol} = selection
      let {columns} = options
      for(let i = startCol; i <= endCol; i++){
        let column = columns[i]
        let item = {headerStyle: {}, style: {}}
        if(type === 'headerStyle'){
          item.headerStyle = data
        }else if(type === 'columnStyle'){
          item.style = data
        }
        merge(column, item)
      }
      tableInstance.updateColumns(columns);
      this.save()
    },
    onChangeColumnEdit(data){
      let { editingCell, options, selection, tableInstance} = this.sheetInstance.activeWorkSheet
      if(!selection) return
      let {startCol, endCol} = selection
      let {columns} = options
      for(let i = startCol; i <= endCol; i++){
        let column = columns[i]
        let item = {editor: data.type, editorConfig: data }
        if(data.disabled){
          merge(item, {
            disableHover: true, editor: false, style: {
              cursor: 'not-allowed'
            }
          })
        }else{
          if(column.style && column.style.cursor){
            delete column.style.cursor
          }
          merge(item, {
            disableHover: false
          })
        }
        merge(column, item)
        // console.log('data', data)
        // console.log('column after merge', column)
        this.save()
      }
      tableInstance.updateColumns(columns);
    },
    save(){
      // const columns = instance.tableInstance.columns
      let data = this.sheetInstance.saveToConfig();
      let config = this.useConf()
      data = cloneDeep(data)
      console.log('data', data)
      data.sheets.forEach(sheet=>{
        sheet.columns.forEach(column=>{
          if(typeof column.editor === 'object'){
            delete column.editor
          }
        })
        if(sheet.filterState){
          delete sheet.filterState
        }
      })
      data.VTablePluginModules = []
      config.data = data
    }
  },
  watch: {
    async height(){
      await this.$nextTick()
      this.sheetInstance.resize()
    }
  },
  computed: {
  }
};
</script>

<style lang="scss" scoped>
::v-deep .vtable-sheet-tab-bar {
  .vtable-sheet-add-button,.vtable-sheet-nav-buttons {
    display: none;
  }
}
</style>
